/*
 * Copyright (c) 2014-2019 2018 xmars All Rights Reserved.
 * ProjectName: xmars
 * FileName: ClassUtil.java
 * Author: YuZheng
 * Date: 18-12-13 下午6:51
 * Version: 1.0
 * LastModified: 18-12-5 下午2:29
 */

package com.topsun.framework.common.core.util;

import com.google.common.base.Throwables;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * 获取com.chenglang下所有类型
 * @author pipi
 */
public class ClassUtil {
    private static final Logger logger = LoggerFactory.getLogger(ClassUtil.class);
    private volatile static List<String> topsunClasses;

    private ClassUtil() {
    }

    /**
     * 获取com.topsun下所有的类名
     *
     * @return
     */
    public static List<String> getTopsunClasses() {
        if (topsunClasses == null) {
            synchronized (ClassUtil.class) {
                if (topsunClasses == null) {
                    try {
                        ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
                        MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resourcePatternResolver);
                        Resource[] resources = resourcePatternResolver.getResources("classpath*:com/topsun/**/*.class");
                        topsunClasses = new ArrayList<>(resources.length);
                        for (Resource resource : resources) {
                            MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
                            topsunClasses.add(metadataReader.getClassMetadata().getClassName());
                        }
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
        return topsunClasses;
    }
}
